package com.zhentao.controller;

import com.zhentao.Exception.vo.ResultVo;
import com.zhentao.service.CartService;
import com.zhentao.utils.JwtUtil;
import com.zhentao.vo.CartAddDTO;
import com.zhentao.vo.CartItemVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Api(tags = "购物车接口")
@RestController
@RequestMapping("/user-service/cart")
@RequiredArgsConstructor
public class CartController {

    private final CartService cartService;
    private final JwtUtil jwtUtil;
    private final HttpServletRequest request;

    private Long getUserId() {
        String token = request.getHeader("Authorization");
        System.err.println("token:" + token);
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        return jwtUtil.getUserIdFromToken(token);
    }

    @ApiOperation("添加商品到购物车")
    @PostMapping("/add")
    public ResultVo<Void> addToCart(@RequestBody CartAddDTO cartAddDTO) {
        Long userId = getUserId();
        System.err.println("userId:" + userId);
        cartService.addToCart(userId, cartAddDTO.getProductId(), cartAddDTO.getQuantity());
        return ResultVo.success();
    }

    @ApiOperation("查询购物车")
    @GetMapping("/list")
    public ResultVo<List<CartItemVO>> getCartItems() {
        Long userId = getUserId();
        return ResultVo.success(cartService.getCartItems(userId));
    }

    @ApiOperation("删除购物车商品")
    @DeleteMapping("/remove/{productId}")
    public ResultVo<Void> removeFromCart(@PathVariable Long productId) {
        Long userId = getUserId();
        cartService.removeFromCart(userId, productId);
        return ResultVo.success();
    }

    @ApiOperation("更新购物车商品数量")
    @PutMapping("/update")
    public ResultVo<Void> updateCartItemQuantity(@RequestParam Long productId, @RequestParam Integer quantity) {
        Long userId = getUserId();
        cartService.updateCartItemQuantity(userId, productId, quantity);
        return ResultVo.success();
    }

    @ApiOperation("清空购物车")
    @DeleteMapping("/clear")
    public ResultVo<Void> clearCart() {
        Long userId = getUserId();
        cartService.clearCart(userId);
        return ResultVo.success();
    }


}
